<template>
  <div class="h-100 position-relative">
    <div class="h-100 position-absolute" style="top:0;z-index:1">
      <div class="h-100">
        <div id="container" style="height: 100%" />
      </div>
    </div>
    <index-header class="position-absolute" style="top:0;z-index:2" />
    <div class="gradients-left position-absolute">
      <div class="flex-column justify-between position-absolute" style="width:69.5%;height:98%;left:3%;top:0">
        <div data-bottom class="h-33">
          <page-header text="生产总值">
            <v-chart v-if="optionSczz.isShow" :options="optionSczz" />
          </page-header>
        </div>
        <div style="height:1%" />
        <div data-bottom class="h-33">
          <page-header text="种植业概况">
            <v-chart v-if="optionZzygk.isShow" :options="optionZzygk" />
          </page-header>
        </div>
        <div style="height:1%" />
        <div data-bottom class="h-33">
          <!-- <div id="heatMap" style="height: 100%" /> -->
          <page-header text="养殖业概况">
            <v-chart v-if="optionYzygk.isShow" :options="optionYzygk" />
          </page-header>
        </div>
      </div>
    </div>
    <div class="gradients-right position-absolute">
      <div class=" flex-column justify-between position-absolute" style="width:69.5%;height:98%;right:3%;top:0">
        <div data-bottom class="h-33">
          <page-header text="新型经营主体">
            <v-chart v-if="optionXxjyzt.isShow" :options="optionXxjyzt" />
          </page-header>
        </div>
        <div style="height:1%" />
        <div data-bottom class="h-33">
          <page-header text="农产品价格趋势">
            <v-chart v-if="optionNcpjgqs.isShow" :options="optionNcpjgqs" />
          </page-header>
        </div>
        <div style="height:1%" />
        <div data-bottom class="h-33">
          <page-header text="农产品产量">
            <v-chart v-if="optionNcpcl.isShow" :options="optionNcpcl" />
          </page-header>
        </div>
      </div>
    </div>
    <div class="gradients-bottom" />
  </div>
</template>

<script>
import IndexHeader from 'header/IndexHeader2.vue'
import AMap from '@/utils/AMap'
import echarts from 'echarts'
import { districts, atmospheric, getTowSideStat, getSingleValue, queryMainProductPriceTrend } from '@/api/connector'
import theme from '@/utils/echarts-theme.json'
import PageHeader from 'header/PageHeader.vue'
import { formatNumber } from '@/utils/app'
import { createInfoWindow } from '@/utils/app'
export default {
  name: 'Test',
  components: {
    IndexHeader,
    PageHeader
  },
  data() {
    return {
      menuLevel: 1,
      map: null,
      amap: '',
      infoWindow: null,
      p1: null,
      time: null,
      p2: null,
      p3: null,
      p4: null,
      heatMap: null,
      showIndex: 0,
      mapData: [],
      path: null,
      starCenter: [108.19848536074164, 34.241771035259845],
      optionSczz: {
        isShow: false,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          },
          // formatter: '{b}<br />{a2}:{c2}%<br />{a1}:{c1}%<br />{a0}:{c0}%'
          formatter: function(params, ticket, callback) {
            var htmlStr = ''
            for (var i = 0; i < params.length; i++) {
              var param = params[i]
              var xName = param.name // x轴的名称
              var seriesName = param.seriesName // 图例名称
              var value = param.value // y轴值
              var color = param.color // 图例颜色
              if (i === 0) {
                htmlStr += xName + '<br/>' // x轴的名称
              }
              htmlStr += '<div>'
              htmlStr +=
                '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>' // 一个点
              htmlStr += seriesName + '：' + formatNumber(value) + '亿元' // 圆点后面显示的文本
              htmlStr += '</div>'
            }
            return htmlStr
          }
        },
        legend: {
          right: 50,
          data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '1%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
          name: '亿元',
          type: 'value'
        },
        series: []
      },
      optionZzygk: {
        isShow: false,
        // title: {
        //   text: '',
        //   x: 'center',
        //   y: 'center',
        //   textStyle: {
        //     fontSize: 14
        //   },
        // },
        title: [
          {
            text: '',
            left: 'center',
            top: '40%',
            textStyle: {
              color: '#fff',
              fontSize: 14
            }
          },
          {
            id: 'statistic',
            text: '亩',
            left: 'center',
            top: '50%',
            textStyle: {
              color: '#fff',
              fontSize: 14
            }
          }
        ],
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}亩({d}%)',
          confine: true
        },
        legend: {
          // orient: 'vertical',
          left: 'center',
          top: 0,
          color: '#E9F7FF',
          data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
        },
        series: [
          {
            center: ['50%', '50%'],
            type: 'pie',
            radius: ['48%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'bottom',
              offset: [0, 50],
              formatter: function(params) {
                if (params.name !== '') {
                  // return params.name + '\n' + '(' + params.percent + '%)';
                  return params.percent + '%'
                  // return formatNumber(params.value) + ' 亩'
                } else {
                  return ''
                }
              }
            },
            labelLine: {
              show: true
            },
            data: []
          }
        ]
      },
      optionYzygk: {
        isShow: true,
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          right: 50,
          data: ['蒸发量', '降水量', '平均温度']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '1%',
          top: '40%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: {
          type: 'value',
          name: '头'
        },
        series: []
      },
      optionNcpcl: {
        isShow: true,
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '40%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          // formatter: '{b}<br />{a2}:{c2}%<br />{a1}:{c1}%<br />{a0}:{c0}%'
          formatter: function(params, ticket, callback) {
            var htmlStr = ''
            for (var i = 0; i < params.length; i++) {
              var param = params[i]
              var xName = param.name // x轴的名称
              var seriesName = param.seriesName // 图例名称
              var value = param.value // y轴值
              var color = param.color // 图例颜色
              if (i === 0) {
                htmlStr += xName + '<br/>' // x轴的名称
              }
              htmlStr += '<div>'
              htmlStr +=
                '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>' // 一个点
              htmlStr += seriesName + '：' + formatNumber(value) + '吨' // 圆点后面显示的文本
              htmlStr += '</div>'
            }
            return htmlStr
          }
        },
        legend: {
          right: 50,
          data: ['蒸发量', '降水量', '平均温度']
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: {
          type: 'value',
          name: '吨'
        },
        series: []
      },
      optionNcpjgqs: {
        isShow: false,
        tooltip: {
          trigger: 'axis',
          formatter: function(params, ticket, callback) {
            var htmlStr = ''
            for (var i = 0; i < params.length; i++) {
              var param = params[i]
              var xName = param.name // x轴的名称
              var seriesName = param.seriesName // 图例名称
              var value = param.value // y轴值
              var color = param.color // 图例颜色
              if (i === 0) {
                htmlStr += xName + '<br/>' // x轴的名称
              }
              htmlStr += '<div>'
              htmlStr +=
                '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>' // 一个点
              htmlStr += seriesName + '：' + formatNumber(value) + '元/吨' // 圆点后面显示的文本
              htmlStr += '</div>'
            }
            return htmlStr
          }
        },
        legend: {
          right: 50,
          data: ['苹果']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '17%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value',
          name: '元/吨'
        },
        series: [
          {
            name: '苹果',
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            areaStyle: {}
          }
        ]
      },
      optionXxjyzt: {
        isShow: false,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          // formatter: '{b}<br />{a2}:{c2}%<br />{a1}:{c1}%<br />{a0}:{c0}%'
          formatter: function(params, ticket, callback) {
            var htmlStr = ''
            for (var i = 0; i < params.length; i++) {
              var param = params[i]
              var xName = param.name // x轴的名称
              var seriesName = param.seriesName // 图例名称
              var value = param.value // y轴值
              var color = param.color // 图例颜色
              if (i === 0) {
                htmlStr += xName + '<br/>' // x轴的名称
              }
              htmlStr += '<div>'
              htmlStr +=
                '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>' // 一个点
              htmlStr += seriesName + '：' + formatNumber(value) + '家' // 圆点后面显示的文本
              htmlStr += '</div>'
            }
            return htmlStr
          }
        },
        legend: {
          right: 50,
          data: ['可用余额', '不可用余额', '收入', '支出']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#808eb7',
              width: 2
            }
          },
          data: []
        },
        yAxis: {
          name: '家',
          splitLine: {
            // 分割线配置
            lineStyle: {
              color: '#AAAAAA56'
            }
          }
        },
        series: []
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initAMap()
    })
  },
  created() {
    this.init()
  },
  beforeDestroy() {
    clearTimeout(this.time)
  },
  methods: {
    init() {
      getTowSideStat({ groupCode: 'SCZZ' }).then((data) => {
        const val = data.body
        const option = this.optionSczz
        option.xAxis.data = val.dateSet
        option.legend.data = val.typeSet
        Object.keys(val.typeValueListMap).forEach((item) => {
          option.series.push({
            name: item,
            type: 'line',
            data: val.typeValueListMap[item]
          })
        })
        option.isShow = true
      })
      getSingleValue({ groupCode: 'ZZYGK' }).then((data) => {
        const val = data.body
        const option = this.optionZzygk
        val.names.shift()
        option.legend.data = val.names
        option.title[0].text = formatNumber(val.values.shift()) // + '\n     亩'
        val.names.forEach((key, index) => {
          option.series[0].data.push({
            value: val.values[index],
            name: key
          })
        })
        option.isShow = true
      })
      getTowSideStat({ groupCode: 'YZYGK' }).then((data) => {
        const val = data.body
        const option = this.optionYzygk
        option.xAxis.data = val.dateSet
        option.legend.data = val.typeSet
        Object.keys(val.typeValueListMap).forEach((item, index) => {
          option.series.push({
            name: item,
            stack: ' ',
            type: 'bar',
            data: val.typeValueListMap[item]
          })
        })
        option.isShow = true
      })
      getTowSideStat({ groupCode: 'NFCPCL' }).then((data) => {
        const val = data.body
        const option = this.optionNcpcl
        option.xAxis.data = val.dateSet
        option.legend.data = val.typeSet
        Object.keys(val.typeValueListMap).forEach((item, index) => {
          option.series.push({
            name: item,
            type: 'bar',
            data: val.typeValueListMap[item]
          })
        })
        option.isShow = true
      })
      queryMainProductPriceTrend().then((data) => {
        const val = data.body.data
        const option = this.optionNcpjgqs
        option.xAxis.data = val.map((item) => {
          return item.publishTime.slice(0, 10)
        })
        option.series[0].data = val.map((item) => item.price)
        option.isShow = true
      })
      getTowSideStat({ groupCode: 'XXJYZT' }).then((data) => {
        const val = data.body
        const option = this.optionXxjyzt
        option.xAxis.data = val.dateSet
        option.legend.data = val.typeSet
        Object.keys(val.typeValueListMap).forEach((item, index) => {
          option.series.push({
            name: item,
            type: 'bar',
            barMaxWidth: 30,
            data: val.typeValueListMap[item]
          })
        })
        option.isShow = true
      })
    },
    drawLoca(data) {
      var layer = new Loca.HeatmapLayer({
        map: this.heatMap
      })
      var list = []
      var i = -1
      var length = data.length
      while (++i < length) {
        var item = data[i]
        list.push({
          coordinate: [item.lng, item.lat],
          count: item.count
        })
      }

      layer.setData(list, {
        lnglat: 'coordinate',
        value: 'count'
      })

      layer.setOptions({
        style: {
          radius: 16,
          color: {
            0.5: '#2c7bb6',
            0.65: '#abd9e9',
            0.7: '#ffffbf',
            0.9: '#fde468',
            1.0: '#d7191c'
          }
        }
      })

      layer.render()
    },
    buildPath() {
      var path = []
      var center = this.map.lngLatToContainer(this.starCenter)
      for (let k = 0; k < 6; k += 1) {
        var ag = ((Math.PI * 60) / 180) * k
        var x = center.x + Math.cos(ag) * 500000
        var y = center.y + Math.sin(ag) * 500000
        path.push((k === 0 ? 'M' : 'L') + x + ' ' + y)
      }
      return path.join(' ') + ' Z'
    },
    onRender() {
      var newPath = this.buildPath()
      this.path.setAttribute('d', newPath)
    },
    async initAMap() {
      try {
        const self = this
        this.amap = await AMap()
        var opts = {
          subdistrict: 0,
          extensions: 'all',
          level: 'city'
        }
        // 利用行政区查询获取边界构建mask路径
        // 也可以直接通过经纬度构建mask路径
        var district = new self.amap.DistrictSearch(opts)
        district.search('咸阳市', function(status, result) {
          var bounds = result.districtList[0].boundaries
          var mask = []
          for (var i = 0; i < bounds.length; i += 1) {
            mask.push([bounds[i]])
          }
          self.map = new self.amap.Map('container', {
            mask: mask,
            center: [108.19848536074164, 34.241771035259845],
            disableSocket: true,
            viewMode: '3D',
            showLabel: false,
            labelzIndex: 130, // 地图标注显示顺序，大于110即可将底图上的默认标注显示在覆盖物（圆、折线、面）之上。
            pitch: 40, // 俯仰角度，默认0，[0,83]，2D地图下无效 。（自V1.4.0开始支持）
            zoom: 16,
            layers: [
              new self.amap.TileLayer.RoadNet({
                // rejectMapMask:true
              }),
              new self.amap.TileLayer.Satellite()
            ]
          })
          // 添加自定义图层
          self.map.plugin(['AMap.CustomLayer'], function() {
            var size = self.map.getSize()
            var canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
            canvas.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
            canvas.setAttribute('width', size.width)
            canvas.setAttribute('height', size.height)

            self.path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
            self.path.onclick = function() {
              // console.log('svg path clicked')
            }
            var styleText = []
            styleText.push('stroke:#132235')
            styleText.push('fill:#132235')
            styleText.push('fill-opacity:0.6')
            self.path.style.cssText = styleText.join(';')

            canvas.appendChild(self.path)
            var customLayer = new self.amap.CustomLayer(canvas, {
              // zooms: [3, 8],
              alwaysRender: true,
              zIndex: 100
            })
            customLayer.render = self.onRender
            self.map.add(customLayer)
          })

          // 添加高度面
          var object3Dlayer = new self.amap.Object3DLayer({ zIndex: 1 })
          self.map.add(object3Dlayer)
          var height = -8000
          var color = '#0088ffcc' // rgba
          var wall = new self.amap.Object3D.Wall({
            path: bounds,
            height: height,
            color: color
          })
          wall.transparent = true
          object3Dlayer.add(wall)

          // 添加描边
          for (let i = 0; i < bounds.length; i += 1) {
            new self.amap.Polyline({
              path: bounds[i],
              strokeColor: '#99ffff',
              strokeWeight: 4,
              map: self.map
            })
          }

          // 添加标记点
          districts().then((res) => {
            const data = res.body.data
            // 添加点
            data.map((item) => {
              const coordinate = JSON.parse(item.coordinate)
              const marker = new self.amap.Marker({
                map: self.map,
                icon: require('./../../../assets/img/map/2.png'),
                position: [coordinate.lng, coordinate.lat],
                zIndex: 301
              })
              marker.on('click', function(e) {
                self.openInfo(e, item)
              })
              self.mapData.push({
                position: [coordinate.lng, coordinate.lat],
                data: item
              })
            })
            self.setMapCenter()
          })
        })
      } catch (err) {
        console.error(err)
      }
    },
    setMapCenter() {
      const self = this
      this.time = setTimeout(() => {
        self.map.setCenter(self.mapData[self.showIndex].position)
        const lnglat = JSON.parse(self.mapData[self.showIndex].data.coordinate)
        self.openInfo({ lnglat }, self.mapData[self.showIndex].data)
        if (self.showIndex === self.mapData.length - 1) {
          self.showIndex = 0
        } else {
          self.showIndex++
        }
        self.setMapCenter()
      }, 8000)
    },
    openInfo(e, item) {
      const self = this
      const title = item.name
      const content = []
      content.push('<div id="mapEcharts"></div>')
      this.infoWindow = new this.amap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content: createInfoWindow(title, content.join('<br/>'), self.map, 0),
        offset: new this.amap.Pixel(16, -45)
      })
      this.infoWindow.open(this.map, e.lnglat)

      setTimeout(() => {
        echarts.registerTheme('themes', theme)
        var myChart = echarts.init(document.getElementById('mapEcharts'), 'themes')
        var option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c}亿元 ({d}%)'
          },
          // title: {
          //   text: (item.primaryProduction + item.secondIndustry + item.thirdIndustry).toFixed(2) + '\n亿元',
          //   x: 'center',
          //   y: '53.5%',
          //   textStyle: {
          //     color: '#E9F7FF',
          //     fontSize: 14
          //   }
          // },
          title: [
            {
              text: (item.primaryProduction + item.secondIndustry + item.thirdIndustry).toFixed(2),
              left: 'center',
              top: '53%',
              textStyle: {
                color: '#fff',
                fontSize: 14
              }
            },
            {
              id: 'statistic1',
              text: '亿元',
              left: 'center',
              top: '60%',
              textStyle: {
                color: '#fff',
                fontSize: 14
              }
            }
          ],
          legend: {
            orient: 'vertical',
            left: 10,
            data: ['第一产业GDP', '第二产业GDP', '第三产业GDP']
          },
          series: [
            {
              name: item.name,
              type: 'pie',
              radius: ['30%', '45%'],
              center: ['center', '60%'],
              avoidLabelOverlap: false,
              label: {
                show: true,
                position: 'bottom',
                offset: [0, 50],
                formatter: function(params) {
                  // let text = params.name;
                  // let value_format = params.value;
                  // let percent_format = '('+params.percent.toFixed(2) + '%)';
                  // if (text.length <= 4) {
                  //   return `${text}\n${percent_format}`;
                  // } else if (text.length > 4 && text.length <= 12) {
                  //   return text = `${text.slice(0, 4)}\n${text.slice(4)}\n${percent_format}`
                  // }

                  // if (params.name !== '') {
                  //   return params.value + ' 亿元'
                  // } else {
                  //   return ''
                  // }

                  return params.percent + '%'
                }
              },
              labelLine: {
                show: true,
                length: 15,
                length2: 5
              },
              emphasis: {
                label: {
                  show: false,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              data: [
                { value: item.primaryProduction, name: '第一产业GDP' },
                { value: item.secondIndustry, name: '第二产业GDP' },
                { value: item.thirdIndustry, name: '第三产业GDP' }
              ]
            }
          ]
        }

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option)
      }, 100)
    },
    districts(item) {
      this.p2 = new Promise((resolve, reject) => {
        districts().then((res) => {
          resolve(res.body.data)
        })
      })
    },
    atmospheric() {
      atmospheric().then((res) => {
        this.drawLoca(res.body.data)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.h-33 {
  height: 32%;
  background: url(~@/assets/img/bg-img.png) no-repeat;
}
div[data-bottom] {
  background: url(~@/assets/img/gradients-left.png) no-repeat;
  background-size: 100% 100% !important;
}
.h-24 {
  height: 23.2%;
}
.amap-info-contentContainer {
  width: 250px;
}
.font-use {
  font-weight: 500;
  color: rgba(255, 255, 255, 1);
  font-size: 20px;
}
.img-100 {
  img {
    height: 100%;
    width: 100%;
  }
}
.gradients-left {
  height: 90.9%;
  top: 10.2%;
  z-index: 2;
  width: 36%;
  background: url(~@/assets/img/bg-img.png) no-repeat;
  background-size: auto 100%;
}
.gradients-right {
  right: 0;
  height: 90.9%;
  top: 10.2%;
  z-index: 2;
  width: 36%;
  background: url(~@/assets/img/bg-img.png) no-repeat;
  background-size: auto 100%;
  background-position: 92% 10.2%;
}
.gradients-bottom {
  z-index: 2;
  width: 28%;
  position: absolute;
  bottom: 0;
  left: 36%;
  height: 20%;
  background: url(~@/assets/img/bg-img.png) no-repeat;
  background-position: 50% 100%;
}
</style>
